const express = require('express')
const mongoose = require('mongoose')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')

// jsonServer 处理
const jsonServer = require('json-server')
const routes = jsonServer.router('./db.json')
const middlewares = jsonServer.defaults()
// End

const UserModel = require('./models/user')

const Auth = require('./middlewares/auth')

const app = express()

// mongoose 链接
mongoose.connect('mongodb://127.0.0.1:27017/maizuo', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('数据库链接成功')
}).catch(() => {
  console.log('数据库链接失败')
})

// req.body
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 跨域处理
app.use((req, res, next) => {
  res.set('Access-Control-Allow-Origin', '*')
  res.set('Access-Control-Allow-Headers', 'content-type')
  next()
})

// 延迟处理
const time = (time = 1500) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}
app.use(async (req, res, next) => {
  await time()
  next()
})

// 登录
app.post('/login', async (req, res) => {
  // 获取前端传递过来的参数
  let username = req.body.username
  let password = req.body.password
  let isOk = false

  const user = await UserModel.findOne({ username })
  if (user) {
    isOk = await bcryptjs.compare(password, user.password)
  }

  if (!isOk) {
    res.send({
      code: -1,
      msg: '用户名或密码不正确'
    })
  }

  // 签发一个 token
  let payload = {
    userId: user._id,
    username: user.username,
    avatar: user.avatar
  }
  let token = jwt.sign(payload, 'MYGOD')

  res.send({
    code: 0,
    msg: '登录成功',
    data: {
      userInfo: payload,
      token
    }
  })
})

// 注册
app.post('/register', async (req, res) => {
  // 获取前段传递过来的参数
  let username = req.body.username
  let password = req.body.password
  let avatar = 'https://gravatar.com/avatar/?d=retro'

  // 判断用户是否已经被注册过了
  const user = await UserModel.findOne({ username })
  if (user) {
    res.send({
      code: -1,
      msg: '用户名已经被注册了'
    })
    return
  }

  const newUser = new UserModel({
    username,
    password: await bcryptjs.hash(password, 10),
    avatar
  })

  await newUser.save()

  res.send({
    code: 0,
    msg: '注册成功'
  })
})

// 获取当前登录用户的个人信息
app.get('/get_user_info', Auth, async (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      userInfo: req.userInfo
    }
  })
})


// 继续处理 jsonserver
app.use(middlewares)
app.use(routes)

app.listen(3000)
